import { storage } from "@/utils/storage"
import api from "@/api/index"
const publicStore = defineStore('public', {
  state: () => ({
		queryForm: {page: 1, limit: 10, params: {}},
		_public: {},
		_model: {},
		count: 0,
		page: 1,
		limit: 20,
		list: [],
		tree: [],
		data: {},
		active: {},
		actIndex: -1,
		current: {},
		datetime: [],
		form: {},
		query: {},
		params: {},
		loading: false,
		empty: false,
		more: false,
		timer: null,
		isTrue: true,
		isFalse: false,
		title: '',
		text: '',
		status: 0,
	}),
    actions: {
		patch(contxt:any) {
			Object.keys(contxt).forEach((key:any)=>{
				storage.set(key, contxt[key])
			})
			this.$patch(contxt)
		},
		async post(contxt:any, headers:any, method:any) {
			return new Promise((resolve) => {
				let strat = new Date().getTime()
				let promiseAll:any = []
				Object.keys(contxt).forEach((key:any)=>{
					promiseAll.push(
						new Promise((resolve, reject) => {
							api[key[0] == '_'?key.slice(1):key](contxt[key], headers, method).then((res:any) => {
								// console.log('响应-------' + (new Date().getTime() - strat) + 'ms', key)
								resolve([key, res.respond? res.respond : []]);
							}).catch((err:any) => {
								console.log('err', err)
								reject(key)
							})
						})   
					)       
				})
				Promise.all(promiseAll.map((promise:any) => promise.catch((err:any) => console.log(err + "---请求错误: " )))).then(res => { 
					let obj:any = {}
					res.forEach((item:any, index:any) => { 
						if(item) obj[item[0][0] == '_'?item[0].slice(1):item[0]] = item[1]; else obj[Object.keys(contxt)[index]] = []
					})
					console.log(contxt, '总响应------', new Date().getTime() - strat + 'ms', Object.keys(obj).length ==1?Object.values(obj)[0]:obj)
					resolve(Object.keys(obj).length ==1?Object.values(obj)[0]:obj)
			    })
		})  
	},
  }
})

export default publicStore